package com.ltmonitor.web.controller.command;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ltmonitor.entity.BasicData;
import com.ltmonitor.entity.JT809Command;
import com.ltmonitor.entity.VehicleData;
import com.ltmonitor.service.IJT809CommandService;
import com.ltmonitor.util.DateUtil;
import com.ltmonitor.util.StringUtil;
import com.ltmonitor.util.T809Constants;
import com.ltmonitor.vo.PaginateResult;
import com.ltmonitor.web.controller.GenericAction;
import com.ltmonitor.web.controller.PaginateAction;
import com.ltmonitor.web.util.JsonMessage;
import com.ltmonitor.web.util.OnlineUser;

/**
 * 下发809平台指令
 * @author admin
 *
 */
@Controller
@RequestMapping("/platformCommand")
public class PlatformCommandAction extends GenericAction {

	@Autowired
	private IJT809CommandService jt809CommandService;

	@RequestMapping("/view.action")
	public String view(long vehicleId, Model m) {
		m.addAttribute("vehicleId", vehicleId);

		m.addAttribute("endDate", new Date());
		m.addAttribute("startDate",
				DateUtil.getDate(new Date(), Calendar.HOUR, -24));
		return "/command/platformCommand";
	}

	@ResponseBody
	@RequestMapping("/send.action")
	public JsonMessage send(String platformCmdType, Date startDate,
			Date endDate, @RequestParam(defaultValue = "0") int vehicleId) {

		JT809Command jc = new JT809Command();
		if (StringUtil.isNullOrEmpty(platformCmdType) == false) {
			try {
				int subCmd = Integer.valueOf(platformCmdType, 16);
				jc.setCmd(0x1200);
				jc.setSubCmd(subCmd);
				jc.setCmdData(DateUtil.datetimeToString(startDate) + ";"
						+ DateUtil.datetimeToString(endDate));

				SendCommand(vehicleId, jc);

				return json(true, jc.getEntityId());
			} catch (Exception ex) {
				log.error(ex.getMessage(), ex);
				return json(false, ex.getMessage());
			}
		} else
			return json(false, "命令不能为空");
	}

	/**
	 * 发送命令，
	 * @param linkCmd 809指令Id 对应于809文档中的指令的Id, 如0x1701 是时效口令上报，0x1007是断开主链路通知等
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/sendLinkRequest.action")
	public JsonMessage sendLinkRequest(int linkCmd) {
		JT809Command jc = new JT809Command();

		if (linkCmd > 0) {
			jc.setCmd(linkCmd);
			try {
				SendCommand(0, jc);

				return json(true, jc.getEntityId());
			} catch (Exception ex) {
				log.error(ex.getMessage(), ex);
				return json(false, ex.getMessage());
			}
		} else
			return json(false, "命令不能为空");
	}


	/**
	 * 分页查询终端命令列表
	 * 
	 * @return
	 */

	@ResponseBody
	@RequestMapping("/paginate.action")
	public PaginateResult query(
			@RequestParam(value = "page", defaultValue = "1") int page,
			@RequestParam(value = "rows", defaultValue = "10") int rows) {
		Map params = new HashMap();
		String queryId = "jt809Command.selectJT809Command";
		if (getOnlineUser() != null) {
			// 只查询用户自己下发的命令
			params.put("userId", getOnlineUser().getEntityId());
		}
		try {
			PaginateResult result = queryService.queryByPagination(queryId,
					params, page, rows);
			for (Object obj : result.getRows()) {
				Map rowData = (Map) obj;
				Integer cmdType = (Integer) rowData.get("cmd");
				Integer subType = (Integer) rowData.get("subCmd");
				subType = subType == 0 ? cmdType : subType;
				String subDescr = T809Constants.getMsgDescr(subType);

				String strCmd = "0x" + Integer.toHexString(cmdType);
				subDescr = "[" + "0x" + Integer.toHexString(subType) + "]"
						+ subDescr;

				rowData.put("cmdType", strCmd);
				rowData.put("subDescr", subDescr);
				String plateColor = "" + rowData.get("plateColor");
				BasicData bd = getBasicDataService().getBasicDataByCode(
						plateColor, "plateColor");
				plateColor = bd != null ? bd.getName() : "";
				rowData.put("plateColor", plateColor);

				String commandStatus = "" + rowData.get("status");
				bd = getBasicDataService().getBasicDataByCode(commandStatus,
						"TCommandStatus");
				if (bd != null) {
					rowData.put("status", bd.getName());
				}
			}
			return result;

		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return new PaginateResult();
	}

	protected void SendCommand(long vehicleId, JT809Command tc) {
		if (vehicleId > 0) {
			VehicleData vd = vehicleDataService.load(vehicleId);
			tc.setPlateNo(vd.getPlateNo());
			tc.setPlateColor((byte) vd.getPlateColor());
		}
		OnlineUser onlineUser = getOnlineUser();
		if (onlineUser != null) {
			tc.setOwner(onlineUser.getName());
			tc.setUserId(onlineUser.getEntityId());
		}
		jt809CommandService.save(tc);
	}

}
